//
//  AIDiaryReplayBean.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/11.
//
/**
 * 评论
 */
import Foundation
import SwiftUI
class AIMemoryRequestBean : Identifiable ,Codable {
    
    var max_tokens: Int64 = configManager.getConfig().AiConfig.maxTokens ?? 1024
    var temperature: Float64 = configManager.getConfig().AiConfig.temperature ?? 0.9
    var top_p: Float64 = configManager.getConfig().AiConfig.top_p ?? 0.95
    var stream = false
    var messages: [MessagesV2]
    var model :String
    
    
    init(model: String?, botRoleBean: RoleBean?, list : [ChatBean], listDiary : [DiaryBean]) {
        self.model = model ?? ""
        let userRoleBean = RoleBean.get(userManager.user, botRoleBean)
        self.messages = AIMemoryRequestBean.getMessagesList(botRoleBean: botRoleBean, userRoleBean: userRoleBean, list: list, listDiary: listDiary)
    }
    
    private static func getMessagesList(botRoleBean: RoleBean?, userRoleBean: RoleBean, list : [ChatBean], listDiary : [DiaryBean]) ->[MessagesV2] {
        
        let time = Date().timeIntervalSince1970
        let ruleDesc = configManager.getConfig().getAiDescribe().aiMemoryDesc2
        let desc = configManager.getConfig().getAiDescribe().aiMemoryDesc
        
        var listMsg : [MessagesV2] = []
        listMsg.append(MessagesV2("system", "记忆提取大师", desc.formatAiChat(botRoleBean, time)))
        
        if let botRoleBean = botRoleBean {
            if list.isEmpty == false {
                let listChatMessage = self.doChatContent(botRoleBean, userRoleBean, list)
                listMsg.append(contentsOf: listChatMessage)
            }
        }
        if listDiary.isEmpty == false {
            let listDiaryMessage = self.doDiary(botRoleBean, userRoleBean, listDiary)
            listMsg.append(contentsOf: listDiaryMessage)
        }
        
        var replaceDesc = "\n\n请用'{{user}}'代替'\(userRoleBean.name ?? "")'"
        if let botName = botRoleBean?.name {
            replaceDesc = replaceDesc +  ",请用'{{char}}'代替'\(botName)'"
        }

        listMsg.append(MessagesV2("user", userRoleBean.name ?? "", ruleDesc.formatAiChat(botRoleBean,time) + replaceDesc))

        return listMsg
    }
    
    //聊天记录
    private static func doChatContent(
        _ botRoleBean: RoleBean,
        _ userRoleBean: RoleBean,
        _ list: [ChatBean]
    ) -> [MessagesV2] {
        let splitString = "\n----\n"

        var listStr : [String] = []
        var listMsg :[MessagesV2] = []
        let time = Date().timeIntervalSince1970

        //添加聊天内容
        var index = 0
        for it in list {
            index = index + 1
            if (it.role != nil) {
                let roleBean = it.role?.isBot() == true ? botRoleBean : userRoleBean
                var text = ""
                if it.contentType == IChatContentType.TYPE_EMOJI_PICTURE.rawValue {
                    let emojiPicture = configManager.getConfig().getAiDescribe().emojiPictureDescribe
                    let desc = (emojiPicture ?? "").formatAiChatContent(it.content ?? "")
                    text = desc.formatAiChat(botRoleBean,time)
                } else {
                    text = it.content ?? ""
                }
                let content = "\(index)、\(TimeUtils.getDate(time: it.time, format: "yyyy-MM-dd"))\n\(roleBean.name ?? ""): \(text)"
                listStr.append(content)
            }
        }
        //聊天记录
        let aiMemoryDescChat = configManager.getConfig().getAiDescribe().aiMemoryDescChat?.formatAiChatContent(splitString + listStr.joined(separator: splitString))
        listMsg.append(MessagesV2("user", userRoleBean.name ?? "", aiMemoryDescChat.formatAiChat(botRoleBean,time)))
        return listMsg
    }
    
    //日记记录
    private static func doDiary(
        _ botRoleBean: RoleBean?,
        _ userRoleBean: RoleBean,
        _ list: [DiaryBean]
    ) -> [MessagesV2] {
        let splitString = "\n----\n"

        var listStr : [String] = []
        var listMsg :[MessagesV2] = []
        let time = Date().timeIntervalSince1970
        let replaceName = "我"

        //添加日记内容， 需要过滤非空内容
        var index = 0
        let letFilter = list.filter { !($0.content ?? "").isEmpty }
        for it in letFilter  {
            index = index + 1
            let roleName = it.roleType == IRoleType.BOT.rawValue ? botRoleBean?.name ?? replaceName : replaceName
            let content = "\(index)、\(TimeUtils.getDate(time: it.time, format: "yyyy-MM-dd"))\n'\(roleName)'写下日记: \(it.content ?? "")"
            listStr.append(content)
        }
        //日记记录
        let aiMemoryDescChat = configManager.getConfig().getAiDescribe().aiMemoryDescDiary?.formatAiChatContent(splitString + listStr.joined(separator: splitString))
        listMsg.append(MessagesV2("user", userRoleBean.name ?? "", aiMemoryDescChat.formatAiChat(botRoleBean,time)))
        return listMsg
    }

}
